package com.example.o3zu.service;

import com.example.o3zu.entity.Student;
import com.example.o3zu.repository.StudentRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;

@Service
public class StudentService {
    @Autowired
    private StudentRepository studentRepository;

    // 创建学生
    public Student createStudent(Student student) {
        return studentRepository.save(student);
    }

    // 获取所有学生
    public List<Student> getAllStudents() {
        return studentRepository.findAll();
    }

    // 根据 ID 获取学生
    public Optional<Student> getStudentById(Long id) {
        return studentRepository.findById(id);
    }

    // 更新学生信息
    public Student updateStudent(Long id, Student updatedStudent) {
        return studentRepository.findById(id)
                .map(student -> {
                    student.setName(updatedStudent.getName());
                    student.setAge(updatedStudent.getAge());
                    return studentRepository.save(student);
                })
                .orElse(null);
    }

    // 删除学生
    public void deleteStudent(Long id) {
        studentRepository.deleteById(id);
    }
}
